package com.ecld.grpc.service;

import com.ecld.grpc.domain.AuthServiceHandler;
import com.ecld.grpc.grpc.*;
import com.ecld.grpc.server.GRpcServer;
import io.grpc.stub.StreamObserver;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AuthServiceImp extends AuthServiceGrpc.AuthServiceImplBase {

    private static final Logger logger = Logger.getLogger(GRpcServer.class.getName());
    private AuthServiceHandler handler = new AuthServiceHandler();

    @Override
    public void changePass(ChangePassRequest request, StreamObserver<ChangePassResponse> responseObserver) {

        logger.log(Level.FINE,"Server Get Change Password Request From User "+ request.getUname());
        String info = handler.doLogin(request.getUname(),request.getPasswd());
        info = info.equals(AuthServiceHandler.LOGIN_SUCCESS_INFO) ?
                handler.doUpdateUser(request.getUname(),request.getNewPasswd()) : info;
        info = info.equals(AuthServiceHandler.UPDATE_SUCCESS_INFO) ? "" : info;
        ChangePassResponse response = ChangePassResponse.newBuilder().setErr(info).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public void auth(AuthRequest request, StreamObserver<AuthResponse> responseObserver) {

        logger.log(Level.FINE,"Server Get Auth Request From User "+ request.getUname());
        String info = handler.doLogin(request.getUname(),request.getPasswd());
        AuthResponse response = info.equals(AuthServiceHandler.LOGIN_SUCCESS_INFO ) ?
                handler.doTouchToken(request.getUname()): AuthResponse.newBuilder().setErr(info).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public void authToken(AuthTokenRequest request, StreamObserver<AuthTokenResponse> responseObserver) {

        logger.log(Level.FINE,"Server Get AuthToken Request From User "+ request.getToken().getUser());
        AuthTokenResponse response = handler.doAuth(request.getToken());
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }


}
